package com.ruoyi.web.controller.utils;

import com.aliyun.oss.OSS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class OssUtil {

    @Autowired
    private OSS ossClient;
    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    /**
     * 上传文件到 OSS
     * @param file      MultipartFile 文件对象
     * @param path      存储路径（如 "images/"）
     * @return          文件访问 URL
     */
    public String uploadFile(MultipartFile file, String path) throws IOException {
        // 生成唯一文件名（防重名）
        String fileName = path + UUID.randomUUID() + "." +
                FilenameUtils.getExtension(file.getOriginalFilename());

        // 上传文件流
        ossClient.putObject(bucketName, fileName, file.getInputStream());

        // 生成可访问的 URL（带时效）
        return generateUrl(fileName);
    }

    private String generateUrl(String fileName) {
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        return ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();
    }

}
